package com.javaenzk.wfx.manager.controller;

import com.javaenzk.wfx.manager.po.TbImages;
import com.javaenzk.wfx.manager.po.Wxb_Good;
import com.javaenzk.wfx.manager.po.Wxb_Good_Type;
import com.javaenzk.wfx.manager.service.IWxbGoodService;
import com.javaenzk.wfx.manager.service.Iimageservice;
import com.javaenzk.wfx.manager.util.AppTools;
import com.javaenzk.wfx.manager.util.ResultJson;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;


/**
 * 商户相关控制层
 */
@Controller
@RequestMapping("/product")
public class MerchantController {

    public static final String IMAGE_BASE_URL="http://localhost/images/";

    @Resource
    private IWxbGoodService wxbGoodService;

    @Autowired
    private Iimageservice iimageservice;

    @RequestMapping("/type")
    public String queryMerchantInfoList(Model model){

        try {

            final List<Wxb_Good_Type> goodtypes = wxbGoodService.queryGoodtype();
            model.addAttribute("goodtypes",goodtypes);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return "goods-add";
    }


    @RequestMapping("/saveGoods")
    @ResponseBody
    public ResultJson addWxbGood(@RequestBody Wxb_Good wxb_good){

        try {
            wxb_good.setGood_Id("69609206");
            wxbGoodService.saveWxbGood(wxb_good);
            return  ResultJson.createSuccessResult(null);
        } catch (Exception e) {
            e.printStackTrace();
            return  ResultJson.createFailResult("1","error");
        }

    }

    @RequestMapping("/upload")
    @ResponseBody
    public  ResultJson uploadPic(MultipartFile file) throws  Exception{

        return upMethod(file);

    }


    public ResultJson upMethod(MultipartFile file) throws  Exception{

        TbImages tbImages = iimageservice.queryImagesByMd5AndType(AppTools.formatMD5String(file.getBytes()), "1");

        /**
         * 查到有这张图片就直接返回url给前端
         */
        if (tbImages != null){
            tbImages.setImageEnable("2");
            iimageservice.save(tbImages);
            return   ResultJson.createSuccessResult(tbImages.getImageUrl());

        }


        //用来连接FTP服务器的工具类
        FTPClient ftp = new FTPClient();
        //连接FTP服务器，默认端口是21
        //连接本机ftp服务器
        ftp.connect("192.168.52.216",21);
        //匿名用户必须使用anonymous登录，密码是邮箱
        boolean login = ftp.login("anonymous", "1756229479@qq.com");
        //获取登录之后的响应状态
        int replyCode = ftp.getReplyCode();
        //没有响应则连接FTP失败
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            System.out.println("获取响应失败");

            return ResultJson.createFailResult("1","获取响应失败");
        }

        //设置接收文件类型为二进制文件
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //FTP服务器上创建images文件夹（如果没有则重新创建文件夹，如果有则使用原来的文件夹）
        ftp.makeDirectory("images");
        //切换ftp上传默认文件夹
        ftp.changeWorkingDirectory("images");

        //将本地图片上传到ftp服务器上
        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
        ftp.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), file.getInputStream());
        //退出登录
        ftp.logout();

        String pathreslut = IMAGE_BASE_URL+fileName;
      //  pathreslut = new String(pathreslut.getBytes("GBK"),"iso-8859-1");


        /**
         * 保存图片
         */
        TbImages tbImages1 = new TbImages();
        tbImages1.setImageEnable("1"); //1.表示图片已在数据库 2.表示图片重复
        tbImages1.setFkId("");
        tbImages1.setImageUrl(pathreslut);
        tbImages1.setImageMd5(AppTools.formatMD5String(file.getBytes()));
        tbImages1.setImageType("0");  // 0.表示图片只是在数据库还没使用 1.表示图片已经使用
        iimageservice.save(tbImages1);

        return   ResultJson.createSuccessResult(IMAGE_BASE_URL+fileName);
    }

    @RequestMapping("/goodlist")
    public String queryList(Model model){
        try {
            final List<Wxb_Good> wxbGoods = wxbGoodService.queryAllwxbGoods();
            model.addAttribute("wxbGoods",wxbGoods);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "merchant-list";
    }
}
